package com.devMode.Builder;

import java.util.Arrays;

/**
 * 生成器模式
 * 封装一个对象的构造过程，并且允许设定任意的初始化顺序
 * 类似Lombok 的 builder
 */
public class BuilderMode {
    public static void main(String[] args) {
        MyStringBuilder msb = new MyStringBuilder();

        final int count = 26;
        for(int i = 0; i<count; i++){
            msb.append((char)('a' + i));
        }

        System.out.println(msb.toString());
    }
}

class AbstractStringBuilder{
    protected char[] value;

    protected int count;

    public AbstractStringBuilder(int capacity){
        count = 0;
        value = new char[capacity];
    }

    public AbstractStringBuilder append(char c){
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }

    public void ensureCapacityInternal(int minmumCapacity){
        if(minmumCapacity - value.length > 0)
            expandCapacity(minmumCapacity);
    }

    private void expandCapacity(int minimumCapacity){
        int newCapacity = value.length >> 1 + 2;
        if(newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        if(newCapacity < 0){
            if(minimumCapacity < 0)
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);
    }
}

class MyStringBuilder extends AbstractStringBuilder{

    public MyStringBuilder() {
        super(16);
    }
    @Override
    public String toString(){
        return new String(value,0,count);
    }
}

